import React, { useState, useEffect } from 'react';
import { motion, useViewportScroll } from 'framer-motion';

const DiagonalImageSlice = ({
  backgroundImage,
  thickness = 200,
  zoomFactor = 2,
  shiftIntensity = 5,
  duration = 0.5,
  hasBorder = false,
  borderColor = '#000',
  hasInnerShadow = false,
  shadowColor = 'rgba(0,0,0,0.5)',
  shadowIntensity = 5,
  zIndex = -1,
  children
}) => {
  const { scrollY } = useViewportScroll();
  const [isScrolling, setIsScrolling] = useState(false);

  // detect scrolling start/stop
  useEffect(() => {
    let timeout;
    const onScroll = () => {
      if (!isScrolling) setIsScrolling(true);
      clearTimeout(timeout);
      timeout = setTimeout(() => setIsScrolling(false), 150);
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => {
      window.removeEventListener('scroll', onScroll);
      clearTimeout(timeout);
    };
  }, [isScrolling]);

  // calculate shift offsets when scrolling
  const shiftOffset = thickness * (shiftIntensity / 20);
  const shiftX = isScrolling ? -shiftOffset : 0;
  const shiftY = isScrolling ? -shiftOffset : 0;

  // styles for optional border / inner shadow
  const borderStyle = hasBorder
    ? { border: `2px solid ${borderColor}` }
    : {};
  const shadowStyle = hasInnerShadow
    ? {
        boxShadow: `inset 0 0 ${shadowIntensity * 5}px ${shadowIntensity *
          2}px ${shadowColor}`,
      }
    : {};

  return (
    <>
      <motion.div
        initial={false}
        animate={{
          scale: isScrolling ? zoomFactor : 1,
          x: shiftX,
          y: shiftY
        }}
        transition={{ duration, ease: 'easeOut' }}
        style={{
          position: 'fixed',
          top: 0,
          left: 0,
          width: '100vw',
          height: '100vh',
          zIndex,
          overflow: 'visible',
          transformOrigin: 'center center',

          // fixed diagonal clip-path, never changes
          clipPath: `polygon(
            0 ${thickness}px,
            100% 0,
            100% calc(100% - ${thickness}px),
            0 100%
          )`,

          // background
          backgroundImage: `url(${backgroundImage})`,
          backgroundSize: 'cover',
          backgroundPosition: 'center',

          // optional effects
          ...borderStyle,
          ...shadowStyle
        }}
      />

      {/* render children on top of the slice */}
      {children}
    </>
  );
};

export default DiagonalImageSlice;